package racing.server;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * Main class for creating and running server.
 * 
 * @author Sarathit Sangtaweep 5510546182
 * @author Veerapat Teeravipark 5510547022
 * @version 2013
 */
public class MainServer extends JFrame {
	private Server server;
	private ServerChat serverChat;
	private JPanel pane;
	private JLabel status;
	private JButton open;
	private JButton close;

	/**
	 * Constructor of the class.
	 * @param server Object of server.
	 * @param serverChat Object of serverChat.
	 */
	public MainServer(Server server, ServerChat serverChat) {
		this.server = server;
		this.serverChat = serverChat;
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		initComponent();
	}

	/**
	 * Construct user interface.
	 */
	private void initComponent() {
		setResizable(false);
		pane = new JPanel();
		pane.setPreferredSize(new Dimension(260, 70));
		status = new JLabel("Status : CLOSE");
		status.setForeground(Color.RED);
		status.setPreferredSize(new Dimension(100, 30));
		open = new JButton("Open Server");
		open.setPreferredSize(new Dimension(120, 30));
		open.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					server.listen();
					serverChat.listen();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (server.isListening() && serverChat.isListening()) {
					open.setEnabled(false);
					close.setEnabled(true);
					status.setForeground(Color.GREEN);
					status.setText("Status : OPEN");
				}
			}
		});
		close = new JButton("Close Server");
		close.setPreferredSize(new Dimension(120, 30));
		close.setEnabled(false);
		close.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					server.close();
					serverChat.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				if (server.isClosed() && serverChat.isClosed()) {
					open.setEnabled(true);
					close.setEnabled(false);
					status.setForeground(Color.RED);
					status.setText("Status : CLOSE");
				}
			}
		});
		pane.add(open);
		pane.add(close);
		pane.add(status);
		getContentPane().add(pane);
	}

	/**
	 * Run user interface for server.
	 */
	public void run() {
		pack();
		setVisible(true);
	}

	/**
	 * Main method for creating and running server.
	 * 
	 * @param args
	 *            command line argument.
	 */
	public static void main(String[] args) {
		Server server = new Server(16668);
		ServerChat serverChat = new ServerChat(16669);
		MainServer ui = new MainServer(server, serverChat);
		ui.run();
	}
}
